package com.njy.cloudalibaba.consumer.filter;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.nacos.common.util.HttpMethod;
import com.njy.cloudalibaba.consumer.wrapper.SecretRequestWrapper;
import com.njy.cloudalibaba.consumer.wrapper.SecretResponseWrapper;
import com.njy.pojo.Constant;
import com.njy.utils.Aes128Utils;
import com.njy.utils.RsaSecretUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Configuration;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.security.NoSuchAlgorithmException;
import java.sql.BatchUpdateException;

@Configuration
public class SecretFilter implements Filter {
    private  Logger logger = LoggerFactory.getLogger(Filter.class);
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        if (((HttpServletRequest) servletRequest).getMethod().equals(HttpMethod.POST)){
            SecretRequestWrapper  requestWrapper= new SecretRequestWrapper((HttpServletRequest) servletRequest);
            SecretResponseWrapper responseWrapper= new SecretResponseWrapper((HttpServletResponse) servletResponse);
            filterChain.doFilter(requestWrapper,responseWrapper);
            responseEncode(servletResponse,responseWrapper.getResponseData());
        }else {
            filterChain.doFilter(servletRequest,servletResponse);
        }

    }

    /**
     * 对返回结果进行加密处理
     * @param servletResponse
     * @param responseData
     */
    private void responseEncode(ServletResponse servletResponse, byte[] responseData) throws IOException {
        String response = new String(responseData);
        logger.info("响应结果长度为-->{}",responseData.length);
        logger.info("响应结果为-->{}",response);
        byte[] encodeResponse = responseEncode(response);
        servletResponse.setContentType("application/json;charset=utf-8");
        servletResponse.setContentLength(encodeResponse.length);
        //把返回值输出到客户端
        ServletOutputStream out = servletResponse.getOutputStream();
        out.write(encodeResponse);
        out.flush();
    }
    private  byte[] responseEncode(String response){
        String aesKey = null;
        try {
            aesKey = Aes128Utils.generateKey();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        String encodeResponse = Aes128Utils.encode(response, aesKey);
        String aesKeyEncode = RsaSecretUtils.privateKeyEncrypt(aesKey, Constant.RSA_PRIVATE_KEY);
        JSONObject json = new JSONObject();
        json.put("aesKey",aesKey);
        json.put("encodeResponse",encodeResponse);
        json.put("aesKeyEncode",aesKeyEncode);
        logger.info("加密后的响应结果-->{}",json.toJSONString());
        byte[] result =json.toJSONString().getBytes(StandardCharsets.UTF_8);
        return result;
    }
}
